//判断用户是否登录
var username = tool.getCookie('username')
if (!username) {
    layer.msg('请先登录', {
        icon: 1,
        time: 1500
    }, function () {
        localStorage.setItem('uel', location.href)
        location.href = '../page/signin.html'
    })
}
// 获取本地数据
var data = localStorage.getItem('data');
// 判断是否获取到
if (!data) {
    $('.cart').html(
        `
            <div class="cart-box">
                <h2>你瞅啥呢，快去购物吧</h2>
                <a href="./list.html">商品展示</a>
            </div>
        `
    )
} else {
    //有数据
    //判断是否有当前这个用户的数据
    var arr = JSON.parse(data).filter(item => item.username === username)
    if (arr.length) {
        //加载数据
        //组合ids
        var ids = arr.map(item => item.goodsid).join();
        //发送ajax请求
        var loadindex = layer.load(1, {
            shade: [.7, '#fff']
        })
        $.get('../php/cart.php', {
            ids
        }, res => {
            var {
                meta: {
                    status,
                    msg
                },
                data
            } = res;
            var str = '';
            data.forEach(item => {
                var number = arr.find(v => v.goodsid === item.id).number;
                str +=
                    `
                    <tr>
                        <td>
                            <input type="checkbox" checked name="selectone">
                        </td>
                        <td>
                            <a hreft="../page/list.html?id=${item.id}">
                            <img src="${item.smallimg}"
                            </a>
                        </td>
                        <td>¥<span>${item.price}</span>元 </td>
                        <td class="number">
                            <button class="reduce">-</button>
                            <input type="number" value="${number}" style="width:50px">
                            <button class="add">+</button>
                        </td>
                        <td class="subtotal">¥<span>${item.price * number}</span>元 </td>
                        <td data-id="${item.id}">
                            <a href="javascript:;" class="btn btn-danger removecart">删除</a>
                        </td>
                    </tr>
                    `
            })
            $('.cart tbody').html(str)
            layer.close(loadindex);
            //全选功能
            selectAll()
            //单选功能
            selectOne()
            //加
            numberAdd()
            //减
            numberReduce()
            //计算小记的功能
            subtotal()
            //总数数量和综合价格
            total()
            // 删除商品
            removeCart()
        }, 'json')
    } else {
        //提示用户挑选商品
        $('.cart').html(
            `
                <div class="cart-box">
                    <h2>你瞅啥呢，快去购物吧</h2>
                    <a href="./list.html">商品展示</a>
                </div>
            `
        )
    }
}


// 全选
function selectAll() {
    $('[name="selectAll"]').click(function () {
        $('[name="selectone"]').prop('checked', $(this).prop('checked'));
        $('[name="selectAll"]').prop('checked', $(this).prop('checked'));
        total()
    })
}

//单选
function selectOne() {
    $('[name="selectone"]').click(function () {
        var arr = Array.prototype.slice.call($('[name="selectone"]'));
        var bool = arr.every(item => item.checked);
        $('[name="selectAll"]').prop('checked', bool)
        total()
    })
}

//数量加
function numberAdd() {

    $('.cart .number button.add').click(function () {
        var number = +$(this).prev().val();
        number++;
        $(this).prev().val(number);

        var data = localStorage.getItem('data')
        data = JSON.parse(data);
        var id = $(this).parent().siblings().last().attr('data-id');
        var obj = data.find(item => item.goodsid === id && item.username === username);
        obj.number++;
        localStorage.setItem('data', JSON.stringify(data));
        subtotal()
        total()
    })
}

function numberReduce() {

    $('.cart .number button.reduce').click(function () {
        var number = +$(this).next().val();
        number--;
        $(this).next().val(number);

        var data = localStorage.getItem('data')
        data = JSON.parse(data);
        var id = $(this).parent().siblings().last().attr('data-id');
        var obj = data.find(item => item.goodsid === id && item.username === username);
        obj.number--;
        localStorage.setItem('data', JSON.stringify(data));
        subtotal()
        total()
    })

}

// 计算小记的功能
function subtotal() {
    $('.cart .number input').each(function (i, v) {
        var sub = v.value * $(v).parent().prev().find('span').text();
        $(v).parent().next().find('span').text(sub)
    })
}
// 总数量和总价格
function total() {
    var totalPrice = 0;
    var totalNumber = 0;
    $('[name="selectone"]:checked').each(function (i, v) {
        totalPrice += $(this).parent().siblings('.subtotal').find('span').text() - 0;
        totalNumber += ($(this).parent().siblings('.number').find('input').val() - 0);
    })
    $('.totalNumber').text(totalNumber);
    $('.totalPrice').text(totalPrice);
}

// 删除购物车
function removeCart() {
    $('.removecart').click(function () {
        layer.confirm('你确定要删除么', {
            btn: ['确定', '再看看']
        }, () => {
            $(this).parent().parent().remove();
            total()
            // 删除本地存储记录
            var data = localStorage.getItem('data');
            data = JSON.parse(data);
            var id = $(this).parent().attr('data-id')
            var index = data.findIndex(item => item.goodsid === id && username === item.username);
            data.splice(index, 1)
            localStorage.setItem('data', JSON.stringify(data))
            layer.msg('删除成功', {
                icon: 6,
                time: 1500
            });
        }, function () {
            layer.msg('取消成功', {
                icon: 6,
                time: 1500
            });
        });
    })
}